import { computed, reactive } from 'vue'
import { usePagination } from 'vue-request'

/**
 * 分页
 * @param {请求方法} requestApiMethod
 * @returns
 */
export default function (requestApiMethod) {
  // 分页查询数据
  const {
    run, data, loading, error, refresh,
    current, total, pageSize
  } = usePagination(requestApiMethod, {
    defaultParams: [],
    pagination: {
      currentKey: 'pager.current', // 请求当前页别名
      pageSizeKey: 'pager.size', // 请求当前页别名
      // 响应数据分页参数KEY
      totalPageKey: 'pagination.pages',  // 总页数
      totalKey: 'pagination.total' // 总记录数
    }
  })

  // 数据表格的数据源
  const dataSource = computed(() => data?.value?.dataList || [])

  // 分页设置
  const pagination = computed(() => ({
    hideOnSinglePage: true, // 只有一页时是否隐藏分页器
    total: total.value,
    current: current.value,
    pageSize: pageSize.value,
    showSizeChanger: true,
    // showQuickJumper: true,
    defaultCurrent: 1,
    defaultPageSize: 10, // 默认每页显示数量
    showTotal: (total) => `[共有 ${total} 条数据]`, // 分页中显示总的数据
    // onShowSizeChange: (current, size) => {
    //   console.info('onShowSizeChange....', page, '========', pageSize)
    //   changePagination(current, size)
    // },
    // onChange: (page, pageSize) => {
    //   console.info('onChange....', page, '========', pageSize)
    //   // changeCurrent(page)
    //   //current.value = page
    //   changePagination(page, pageSize)
    // }
  }))
  //
  const searchData = reactive({}) 
  // 表分页
  const handleTableChange = (pag, filters, sorter) => {
    run({
      'pager.size': pag.pageSize,
      'pager.current': pag?.current,
      sortField: sorter.field,
      sortOrder: sorter.order,
      ...filters,
      ...searchData
    })
  }
  const handleSearch =(searchkey)=>{
    // alert(JSON.stringify(searchkey))
    Object.assign(searchData, searchkey)
    run({
      'pager.size': 10,
      'pager.current': 1,
      ...searchData
    })
  }
  return {
    refresh, run,
    error,
    loading,
    data,
    dataSource,
    pagination,
    handleTableChange,
    handleSearch
  }
}